/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wb.picmover.handler;

import cn.ac.iie.di.wb.picmover.util.FtpTools;
import cn.ac.iie.di.wb.picmover.util.GlobalParameters;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class PicThreadPoolTask implements Runnable {

    static private final Logger logger = Logger.getLogger(PicThreadPoolTask.class.getName());
    private Message list;
    private FTPClient createFtpClient = null;
    private FTPClient deleteFtpClient = null;
    private String ftpip = "";
    private String ftppath = "";
    private Integer ftpport = -1;
    private String username = "";
    private String passwd = "";

    public PicThreadPoolTask(Message list) {
        this.list = list;
    }

    @Override
    public void run() {
        logger.info("get " + list.getData().size() + " datas form picHandlerQueue!");
        long starttime = System.currentTimeMillis();
        long connFtpTime = 0;
        int addColId = 0;
        int downnum = 0;
        int sumpic = 0;
        int emptynum = 0;
        FtpTools ftpTools = new FtpTools();
        List<Object[]> dataList = list.getData();
        boolean flag = true;

        String[] colNames = list.getColNames();
        for (int id = 0; id < colNames.length; id++) {
            if (colNames[id].equals(GlobalParameters.addColName)) {
                addColId = id;
                logger.debug("******have " + GlobalParameters.addColName + " and the colId is " + addColId);
                break;
            }
        }

        try {
            for (int i = 0; i < dataList.size(); i++) {
                Object[] dataArr = dataList.get(i);
                String[] picArr = new String[]{};
                try {
                    picArr = (String[]) dataArr[addColId];
                } catch (Exception e) {
                    logger.error(GlobalParameters.addColName + " is " + addColId + "******the error message " + Arrays.toString(dataList.get(i)));
                    logger.error(Arrays.toString(colNames));
                    logger.error(e.getMessage(), e);
                }

                //石鹏峰传的数据没有这个字段，nullPointExceotion
                if (picArr.length != 0) {
                    for (String picStr : picArr) {
                        sumpic++;
                        if (!picStr.isEmpty()) {
                            if (flag) {
                                for (String[] ftp : GlobalParameters.ftplist) {

//                                    if (picStr.split("[|]")[2].equals(ftp[0])) {
                                    while (true) {
                                        createFtpClient = ftpTools.createFtpClient(ftp[0], Integer.parseInt(ftp[1]), ftp[2], ftp[3]);
                                        if (createFtpClient != null) {
                                            break;
                                        } else {
                                            logger.warn("ftp createClient error!");
                                        }
                                    }

                                    ftpip = ftp[0];
                                    ftppath = ftp[4];
                                    ftpport = Integer.parseInt(ftp[1]);
                                    username = ftp[2];
                                    passwd = "111111";
                                    logger.info("ftpip" + ftpip);
                                    logger.info("ftppath" + ftppath);
                                    logger.info("ftpport" + ftpport);
                                    logger.info("username" + username);
                                    logger.info("passwd" + passwd);
                                    flag = false;
                                    connFtpTime = System.currentTimeMillis();
                                    break;
//                                    }
                                }
                            }

                            try {
                                String printWorkingDirectory = createFtpClient.printWorkingDirectory();
                                logger.debug("currentPath " + printWorkingDirectory);
                            } catch (Exception e) {
                                logger.error("ftpclient lose efficacy, create a new ftpclient.");
                                if (createFtpClient != null) {
                                    ftpTools.destroyFtpClient(createFtpClient);
                                }
                                createFtpClient = ftpTools.createFtpClient(ftpip, ftpport, username, passwd);
                            }

                            //需要下载文件
                            boolean downFile = ftpTools.downDataFile(createFtpClient, ftpip, ftppath, GlobalParameters.localpath, picStr.split("[|]")[1], GlobalParameters.ftptimeout);
                            if (!downFile) {
                                logger.error("====download " + picStr.split("[|]")[1] + " from " + ftpip + " failed.");
                            } else {
                                if (createFtpClient != null) {
                                    ftpTools.destroyFtpClient(createFtpClient);
                                }
                                downnum++;
                                while (true) {
                                    createFtpClient = ftpTools.createFtpClient(ftpip, ftpport, username, passwd);
                                    if (createFtpClient != null) {
                                        break;
                                    } else {
                                        logger.warn("ftp createClient error!");
                                    }

                                }
                                boolean upload = ftpTools.uploadFile(createFtpClient, ftpip, ftppath, picStr.split("[|]")[1], GlobalParameters.ftptimeout);
                                if (!upload) {
                                    logger.error("====upload " + picStr.split("[|]")[1] + " to " + ftpip + " failed.");
                                }
                            }
                        } else {
                            emptynum++;
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("download file or copy file failed from " + ftpip + " ,cause " + e.getMessage(), e);
        } finally {
            //关闭ftp连接
            if (createFtpClient != null) {
                ftpTools.destroyFtpClient(createFtpClient);
            }
        }

        logger.info("download ftp file size " + downnum + " / " + sumpic + " from '" + ftpip + "' and the emptyPic size " + emptynum + " , use " + (System.currentTimeMillis() - starttime) + " ms totally. ConnFtp use " + (connFtpTime - starttime) + " ms.");
//        try {
//            GlobalParameters.picSendQueue.put(list);
//        } catch (InterruptedException ex) {
//            logger.error("put data to picSendQueue error ,cause " + ex.getMessage(), ex);
//        }
//        while (!GlobalParameters.picSendQueue.offer(list)) {
//            logger.warn("picSendQueue has no space to offer " + list.getData().size());
//        }
//        logger.info("offer " + list.getData().size() + " to picSendHandlerQueue!");
    }

}
